﻿using System;
using System.Collections;
using System.Data;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Framework.Model;
using Framework.Sql;

namespace Framework.Metadata
{
    public class EntityMetadata : ColumnPropertyMetadata
    {
        public EntityMetadata(PropertyInfo propertyInfo) : base(propertyInfo) { }

        public override void UpdateObject(object o, IDataRecord record, Func<Type, LambdaExpression, Action<SelectSqlBuilder, Type>, IEnumerable> find)
        {
            var dbValue = record[ColumnName];

            var member = PropertyInfo.PropertyType.GetProperty("Id");
            var parameter = Expression.Parameter(PropertyInfo.PropertyType);
            var memberAccess = Expression.MakeMemberAccess(parameter, member);
            var equal = Expression.Equal(memberAccess, Expression.Constant(Convert.ToInt32(dbValue)));
            var lambda = Expression.Lambda(equal, parameter);

            var obj = find(PropertyInfo.PropertyType, lambda, null).Cast<object>().FirstOrDefault();
            PropertyInfo.SetValue(o, obj, null);
        }

        public override void ModifySql(InsertSqlBuilder builder, object value)
        {
            var propertyValue = ((IId)PropertyInfo.GetValue(value, null)).Id;
            builder.AddUpdateColumn(ColumnName, propertyValue);
        }
    }
}